package org.wu.framework.lazy.orm.core.persistence.util;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * sql 信息转换
 */
public class SqlMessageFormatUtil {


    /**
     * @param pattern   select * from {0}
     * @param arguments user
     * @return select * from user
     */
    public static String format(String pattern, Object... arguments) {
        int index = 0;
        for (Object argument : arguments) {
            String target = "\\{" + index + "}";
            if (null == argument) {
                continue;
            }
            Object replacement = argument;
            if (AtomicReference.class.isAssignableFrom(argument.getClass())) {
                replacement = ((AtomicReference<?>) argument).get();
            }
            pattern = pattern.replaceAll(target, replacement.toString());
            index++;
        }
        return pattern;
    }

    /**
     * @param pattern   select * from #{table}
     * @param arguments user
     * @return select * from user
     */
    public static String format(String pattern, Map<String, Object> arguments) {

        for (Map.Entry<String, Object> stringObjectEntry : arguments.entrySet()) {
            String key = stringObjectEntry.getKey();
            Object value = stringObjectEntry.getValue();
            String target = "#\\{" + key + "}";
            Object replacement = value;
            if (AtomicReference.class.isAssignableFrom(value.getClass())) {
                replacement = ((AtomicReference<?>) value).get();
            }
            pattern = pattern.replaceAll(target, replacement.toString());
        }
        return pattern;
    }

    public static void main(String[] args) {
        String xx = "select * from {0}";
        System.out.println(xx.replaceAll("\\{0}", "table"));

        String text = "select * from #{table} where id=#{id}";
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("table", "user");
        arguments.put("id", "1");
        System.out.println(format(text, arguments));
    }
}
